<template>
	<scroll-view class="post-content" scroll-y="true" :scroll-into-view="scrollIntoViewId">
		<view class="post">
			<view class="item">
				<view class="level" >
					<view class="level-left" @click="toHomePage(postDetail)">
						<u-avatar class="avatar" mode="aspectFill" :src="$store.state.userInfo.avatar" size="35"></u-avatar>
						<view class="">
							<view class="name">{{$store.state.userInfo.nickName}}</view>
							<view class="date">{{postDetail.createTime}}</view>
						</view>
					</view>
						<view class="level-right" v-show="postDetail.isFollowed==0&&postDetail.userId!=$store.state.userInfo.userId" @click="onFollow()">
							<u-icon name="plus" class="icon" :plain="true" size="14" shape="circle" color="#FE4E4E"></u-icon>关注
						</view>
						<view class="level-right active" v-show="postDetail.isFollowed==1&&postDetail.userId!=$store.state.userInfo.userId" @click="onFollow()" >
							<u-icon name="checkmark" class="icon" :plain="true" size="14" shape="circle" color="#ccc"></u-icon>已关注
						</view>
				</view>
				
				<post-shrink
					:text="postDetail.content" 
					:line="30"
				/>
				
				<view class="level album">
					<view v-if="postDetail.files&&postDetail.files.length === 4 && postDetail.files[0].isImage === 1" class="grid-tianzi">
						<view 
							v-for="(file, fileIndex) in postDetail.files" 
							:key="file.fileUrl + fileIndex" 
							class="grid-tianzi-item"
							@click.stop="previewImage(postDetail.files, fileIndex)"
						>
							<u-image 
								:src="file.fileUrl" 
								width="189" 
								height="189"
								mode="aspectFill"
							></u-image>
						</view>
					</view>
					<u-album
						v-else-if="postDetail.files&&postDetail.files.length!=4 && postDetail.files[0].isImage==1" 
						:urls="postDetail.files"
						keyName="fileUrl"
						:multipleSize="'222rpx'" 
						:singleSize="370"
					></u-album>
					<DomVideoPlayer
						v-if="postDetail.files&&postDetail.files.length!=0&&postDetail.files[0].isImage==0"
						@top.stop="fullScreen(index)"
						:src="postDetail.files[0].fileUrl"
						loop
						autoplay
					/>
				</view>
				<view class="label level">
					<text v-for="i in postTopics" :key="i.title">#{{i.title}}</text>
				</view>

				<u-tabs :list="tabList" lineColor="#ff9900" @click="tabClick" :current="currentTab"></u-tabs>
				<view class="post-actions">
					<view class="post-actions-item" @click="shareWx()">
						<u-icon name="share" size="24" color="#000"></u-icon>
						<text class="post-actions-item-text">转发</text>
					</view>
					<view class="post-actions-item" @click="openCommentTab()">
						<u-icon name="chat" size="24" color="#000"></u-icon>
						<text class="post-actions-item-text">评论</text>
					</view>
					<view class="post-actions-item" @click="dropCollect()">
						<u-icon :name="postDetail.isCollected==1?'star-fill':'star'" :color="postDetail.isCollected==1?'#ff5a5f':'#000'" size="24"></u-icon>
						<text class="post-actions-item-text">收藏</text>
					</view>
				</view>
				<view v-if="currentTab === 0" class="comment-section" id="comment">
					<CComment 
						@touchstart="$refs.ccRef.closeComment()"  
						ref="ccRef" 
						:userInfo="authorInfo" 
						:tableData="tableData" 
						:tableTotal="0" 
						@likeFun="likeFun" 
						:deleteMode="deleteMode"
						@avatarFun = "avatarFun"
						@replyFun="replyFun"
						@deleteFun="deleteFun"
					></CComment>
				</view>

				<view v-if="currentTab === 1" class="likes-section">
					<u-empty mode="data" v-if="likesList.length === 0" text="暂无点赞记录" style="margin-top: 50rpx;"></u-empty>
					<view v-else>
						<view class="like-item" v-for="(item, index) in likesList" :key="item.userId" @click="goToOthersPage(item, index)">
							<u-avatar class="like-item__avatar-comp" mode="aspectFill" :src="item.avatar" size="35"></u-avatar>
							<view class="like-item__info">
								<text class="like-item__name">{{ item.nickName }}</text>
								<text class="like-item__desc">{{formatDateTime(item.createdAt)}}赞了这篇帖子</text>
							</view>
							<u-icon class="like-item__arrow" name="arrow-right" color="#999" size="16"></u-icon>
						</view>
					</view>
					<u-divider v-if="likesList.length > 0" style="margin: 50rpx;" :textSize="12" text="到底了哦~"></u-divider>
				</view>
			</view>
		</view>
		
	</scroll-view>
</template>

<script>
	import CComment from "@/components/XJ-comment/index";
	import PostShrink from "@/components/post-shrink/post-shrink"
	import { 
		getPostDetails,
		getClientFollow,
		getCommentList,
		getCommentChildrenList,
		addComment,
		removeComment,
		addCommentLike,
		cancelCommentLike,
		postClientCollect,
		postCancelCollect,
		getClientLike
	} from '@/request/api.js'
	import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer.vue'
	export default {
		components: {
			DomVideoPlayer,
			CComment,
			PostShrink
		},
		data() {
			return {
				postId:null,
				postCreatorId:null,
				isScroll:false,
				postDetail:{},
				ccRef: null,
				userInfo: {},
				authorInfo:{},
				tableTotal: 0,
				tableData: [],
				deleteMode: "all",
				scrollIntoViewId: '',
				postTopics:[],
				tabList: [{ name: '评论 0' }, { name: '赞 0' }],
				currentTab: 0,
				likesList: [],
				likesTotal: 0,
			}
		},
		watch:{
			postDetail(newVal) {
				console.log('newVal',newVal);
			},
			likesTotal(newVal) {
				this.$set(this.tabList[1], 'name', '赞 ' + newVal);
			},
			tableTotal(newVal) {
				this.$set(this.tabList[0], 'name', '评论 ' + newVal);
			}
		},
		onLoad(options) {
			this.initData()
		},
		methods: {
			initData(){
				  const eventChannel = this.getOpenerEventChannel();
				eventChannel.on('sendInitData', (res) => {
					let data = JSON.parse(res.data)
					this.postId = data.item.id
					this.postCreatorId = data.item.userId
					this.authorInfo = {
						id: data.item.userId,
						user_name: data.item.nickName,
						user_avatar: data.item.avatar,
					}
					this.tableTotal = data.item.commentCount
					this.isScroll = data.scroll
					this.postDetail = data.item
					this.getPostDetail()
					this.getCommentLists()
					this.getPostLikes() 
				});
			},
			formatDateTime(time) {
				if(!time) return null
				const date = new Date(time);
			    let year = date.getFullYear();
			    let month = ("0" + (date.getMonth() + 1)).slice(-2);
			    let day = ("0" + date.getDate()).slice(-2);
			    let hours = ("0" + date.getHours()).slice(-2);
			    let minutes = ("0" + date.getMinutes()).slice(-2);
			    let seconds = ("0" + date.getSeconds()).slice(-2);
			    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			previewImage(files, currentIndex) {
				const urls = files.map(file => file.fileUrl);
				uni.previewImage({
					urls: urls,
					current: currentIndex,
					fail: (err) => {
					}
				});
			},
			getCommentLists(){
				getCommentList(this.postId).then((res)=>{
					this.tableData = res.data.rows&&res.data.rows.map(data=>{
						this.getCommentChildrenList(data.commentId)
						return{
							id: data.commentId,
							parent_id: null,
							reply_id: null,
							reply_name: null,
							user_name: data.nickName,
							user_avatar: data.avatar,
							user_content: data.content,
							is_like: data.isLiked,
							like_count: data.likeCount,
							create_time:data.createTime,
							user_id:data.userId,
						}
					})
					
				})
			},
			getCommentChildrenList(commentId){
				getCommentChildrenList(commentId).then((res)=>{
					let replyList = res.data.rows&& res.data.rows.map(data=>{
						return{
							id: data.commentId,
							parent_id: data.parentId,
							reply_id: data.replyToUserId,
							reply_name: data.replyToName,
							user_name: data.nickName,
							user_avatar: data.avatar,
							user_content: data.content,
							is_like: data.isLiked,
							like_count: data.likeCount,
							create_time:data.createTime,
							user_id:data.userId,
						}
					})
					console.log("replyList",replyList);
					this.tableData.push(...replyList)
					console.log("this.tableData",this.tableData);
				})
			},
			getPostDetail(){
				getPostDetails(this.postId).then((res)=>{
					this.postTopics = res.data.data.postTopics
					
					if(this.isScroll=='true' && this.currentTab === 0){
						this.scrollToPosition()
					}
				})
			},
			scrollToPosition() {
				this.$nextTick(() => {
				    this.scrollIntoViewId = 'comment';
				});
			},
			onFollow(item,index){
				this.postDetail.isFollowed = this.postDetail.isFollowed == 0 ? this.postDetail.isFollowed = 1 : this.postDetail.isFollowed=0;
				getClientFollow({userId:this.postDetail.userId}).then(res=>{
					this.sendParent(4)
				})
			},
			onUnFollow(item,index){
				this.postDetail.isGZ = false
				uni.showToast({
					title: '取消关注成功！'
				});
			},
			onChat(item){
				uni.navigateTo({
					url: '/pages_sub/user/chat/chat?userId='+this.postDetail.id
				});
			},
			openCommentTab(){
				this.currentTab = 0;
				this.$nextTick(() => {
					if (this.$refs.ccRef) {
						this.$refs.ccRef.newCommentFun();
					}
					this.scrollToPosition();
				});
			},
			likeFun(params, callback) {
				if(params.params.is_like){
					addCommentLike(params.params.id).then(res=>{
						if(res.data.code!=200){
							callback(params)
						}
					})
				}else{
					cancelCommentLike(params.params.id).then(res=>{
						if(res.data.code!=200){
							callback(params)
						}
					})
				}
			},
			avatarFun(id){
				uni.navigateTo({
					url: '/pages_sub/user/others/others?userId='+id,
				});
			},
			replyFun(params, callback) {
				console.log("params",params);
				let data = {
					postId:new Number(this.postId),
					userId:new Number(this.$store.state.userInfo.userId),
					parentId:new Number(params.params.parent_id )|| null,
					replyToUserId: new Number(params.params.user_id ) || null,
					content: params.params.user_content || null,
					postCreatorId: new Number(this.postCreatorId )
				}
				addComment( data ).then((res) => {
				   if (res.data.code==500) {
				   	uni.$u.toast(res.data.msg);
				   }else{
						const data = { id: res.data.data.commentId }; 
						this.sendParent(1)
						this.getCommentLists(); 
						this.tableTotal++
						callback(data); 
				    }
				});
			},
			sendParent(type){
				const eventChannel = this.getOpenerEventChannel();
				let returnData = { 
					id: this.postId,
					userId:this.authorInfo.id, 
					type: type,
					isLiked:this.postDetail.isLiked,
					collectCount:this.postDetail.isCollected?this.postDetail.collectCount+1:this.postDetail.collectCount-1,
					isCollected:this.postDetail.isCollected,
					isFollowed:this.postDetail.isFollowed ,
				}
				eventChannel.emit('returnData', returnData);
			},
			deleteFun({ params, mode }, callback) {
				switch (this.deleteMode) {
					case "bind":
						setTimeout(() => {
							this.getCommentLists();
							callback();
						}, 500); 
					break;
					case "only":
						setTimeout(() => {
							this.getCommentLists();
							callback();
						}, 500); 
					break;
					default:
						setTimeout(() => {
							this.getCommentLists();
							callback();
						}, 500); 
					break;
				}
			},
			shareWx(){
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					href: "http://uniapp.dcloud.io/",
					title: this.postDetail.name,
					summary: this.postDetail.describe,
					imageUrl: this.postDetail.avatar,
					success: function (res) {
					},
					fail: function (err) {
					}
				});
			},
			dropLike(){
				this.postDetail.like = !this.postDetail.like
				if(this.postDetail.like){
					this.postDetail.like_num++
					uni.showToast({
						title: "点赞成功",
						icon: 'success',
					})
				}else{
					this.postDetail.like_num--
					uni.showToast({
						title: "已取消点赞",
						icon: 'error',
					})
				}
				
			},
			dropCollect(){
				let is_collect = this.postDetail.isCollected==0?true:false
				if(is_collect){
					postClientCollect(this.postDetail.id).then(res=>{
						this.postDetail.isCollected = 1
						this.sendParent(2)
					})
				}else{
					postCancelCollect(this.postDetail.id).then(res=>{
						this.postDetail.isCollected = 0
						this.sendParent(2)
					})
				}
			},
			tabClick(item) {
				this.currentTab = item.index;
				if (item.index === 1 && this.likesList.length === 0) {
				}
				if (item.index === 0 && this.isScroll == 'true') {
					 this.scrollToPosition();
				}
			},
			getPostLikes() {
				let params = {
					postId:this.postId,
					pageNum:1
					
				}
				getClientLike(params).then(res=>{
					if (res.data.code === 200) {
						let mockResponse = res.data
						this.likesList = mockResponse.rows.map(like => ({
							...like,
							isFollowed: like.isFollowed !== undefined ? like.isFollowed : 0
						}));
						this.likesTotal = parseInt(mockResponse.total) || this.likesList.length;
						this.$set(this.tabList[1], 'name', '赞 ' + this.likesTotal);
						console.log('模拟获取点赞列表:', this.likesList);
					} else {
						console.error('获取点赞列表失败:', mockResponse.msg);
						this.likesList = [];
						this.likesTotal = 0;
						this.$set(this.tabList[1], 'name', '赞 ' + this.likesTotal);
					}
				})
			},
			goToOthersPage(userItem, indexInList) {
				let initialData = {
					userId: userItem.userId,
					isFollowed: userItem.isFollowed > 0 ? true : false 
				};
				uni.navigateTo({
					url: '/pages_sub/user/others/others',
					events: {
						returnData: (returnedData) => {
							if (returnedData.userId === userItem.userId && typeof returnedData.isFollowed !== 'undefined') {
								this.$set(this.likesList[indexInList], 'isFollowed', returnedData.isFollowed ? 1 : 0);
							}
						}
					},
					success: (res) => {
						res.eventChannel.emit('sendInitData', { data: JSON.stringify(initialData) });
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.post-content{
		height: calc(100vh - 100rpx); 
		padding-bottom: 80rpx; 
	}
	.album{
		display: inline-block;
		margin-top: 15rpx;
		position: relative;
		z-index: 1;
		.grid-tianzi {
			display: grid;
			flex: 1;
			grid-template-columns: repeat(2, 1fr);
			grid-auto-rows: 1fr;
			gap: 4px;
			
			.grid-tianzi-item {
				aspect-ratio: 1 / 1;
				overflow: hidden;
			}
		}
	}
.post{
	background-color: #FFFFFF;
	.item{
		background-color: #FFFFFF;
		padding: 10rpx 30rpx 0 30rpx;
	}
	.avatar{
		width: 100rpx;
		height: 100rpx;
		margin-right: 20rpx;
		border-radius: 50%;
		border: 1rpx solid #FFAE1A;
	}
	.level{
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 15rpx 0;
		.level-left{
			display: flex;
			align-items: center;
		}
		.level-right{
			display: flex;
			color: #FE4E4E;
			border: 1rpx solid #FE4E4E;
			border-radius: 50rpx;
			font-size: 26rpx;
			padding: 5rpx 15rpx;
			.icon{
				margin-right: 5rpx;
			}
		}
		.active{
			color: #cccccc;
			border: 1rpx solid #cccccc;
		}
	}
	.name{
		font-size: 32rpx;
	}
	.date{
		color: #787878;
		font-size: 22rpx;
		margin-top: 5rpx;
	}
	.describe{
		
	}
	.label{
		font-size: 24rpx;
		color: #FFAE1A;
	}
	.image:nth-child(2){
		margin: 0 15rpx;
	}
	.image{
		justify-content: space-between;
	}
}
.post-actions{
	display: flex;
	    color: #000;
	    justify-content: space-between;
	    font-size: 13px;
	    position: fixed;
	    bottom: 0px;
	    padding-bottom: 11px;
	    left: 27px;
	    right: 27px;
	.post-actions-item{
		display: flex;
		align-items: center;
		flex-direction: column;
		&-text{
			min-width: 40rpx;
			text-align: center;
			font-size: 20rpx; 
			margin-top: 4rpx;
		}
	}
	.image{
		width: 48rpx;
		height: 48rpx;
		margin-right: 10rpx;
	}
	text{
	}
}

.comment-section, .likes-section {
	padding-bottom: 20rpx; 
	border-top: 1rpx solid #f8f8f8;
}

.like-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;

  &:last-child {
    border-bottom: none;
  }

  &__avatar-comp {
    margin-right: 20rpx;
	flex-shrink: 0;
  }

  &__info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
	min-width: 0; // Prevents text overflow issues
  }

  &__name {
    font-size: 30rpx;
    color: #333;
    line-height: 1.4;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
  }

  &__desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 4rpx;
    line-height: 1.4;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
  }
  
  &__arrow {
    margin-left: 20rpx;
	flex-shrink: 0;
	color: #c0c4cc; // A softer arrow color
  }
}
</style>